package com.hq.tomato.ms.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;

/**
 * @Author huqiang
 * @Description //TODO  jackson工具类
 * @Date  2019-08-05
 * @return
 */
@Slf4j
public class JacksonUtil {
	private static ObjectMapper timeZoneMapper = new ObjectMapper();
	static {
		timeZoneMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		timeZoneMapper.registerModule(new JavaTimeModule());
		timeZoneMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
	}



	public static String bean2JsonByZoneTime(Object obj)  {
		try {
			StringWriter sw = new StringWriter();
			JsonGenerator gen = new JsonFactory().createGenerator(sw);
			timeZoneMapper.writeValue(gen, obj);
			gen.close();
			return sw.toString();
		}catch (Exception e){
			log.error("序列化异常,异常信息为:{}",e.getMessage());
		}
		return null;
	}



	public static <T> T json2BeanByZoneTime(String jsonStr, Class<T> objClass){
		try {
			return timeZoneMapper.readValue(jsonStr, objClass);
		}catch (Exception e){
			log.error("【反序列化异常,异常信息为:{}】",e.getMessage());
		}
		return null;
	}



}